﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace ConsoleApp.Infrastructure.Rmq
{
    public class RmqPullMessageService
    {
        public static List<T> GetMessagesBulk<T>(int count, string queueName, RmqOption uri)
        {
            List<T> list = new List<T>();
            int i = 0;
            using IModel model = RmqConnectPoolFactory.GetClientPool(uri).GetConnect().GetChannel();
            for (; i < count; i++)
            {
                _ = string.Empty;
                try
                {
                    BasicGetResult basicGetResult = model.BasicGet(queueName, autoAck: true);
                    if (basicGetResult != null)
                    {
                        T item = JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(basicGetResult.Body));
                        list.Add(item);
                        continue;
                    }

                    return list;
                }
                catch (Exception ex)
                {
                    RmqLogHelper.WriteError("拉取消息异常：" + ex.ToString());
                }
            }

            return list;
        }

        public static void Clear(RmqOption uri, string queueName)
        {
            using IModel model = RmqConnectPoolFactory.GetClientPool(uri).GetConnect().GetChannel();
            while (true)
            {
                try
                {
                    model.BasicGet(queueName, autoAck: true);
                }
                catch (Exception ex)
                {
                    RmqLogHelper.WriteError("拉取消息异常：" + ex.ToString());
                }
            }
        }

        public static void DeleteQueue(RmqOption uri, string queueName)
        {
            using IModel model = RmqConnectPoolFactory.GetClientPool(uri).GetConnect().GetChannel();
            try
            {
                model.QueueDelete(queueName, ifUnused: true, ifEmpty: false);
                Console.WriteLine(queueName);
            }
            catch (Exception)
            {
                RmqLogHelper.WriteError("删除队列异常：" + queueName);
            }
        }
    }
}
